import json

CH_JSON = r"D:\Documents\work\video\gitee\2\ch.json" # 中文字幕json

output_subtitles_file = 'ch.txt' # 带时间戳中文字幕
output_texts_file = 'chdoc.txt' # 纯文本中文字幕


# 从字幕片段列表中提取字幕文本和时间信息
def getTxt(segments):
    return " ".join(seg.get("utf8", "") for seg in segments if "utf8" in seg)

# 解析 JSON 字幕文件
def decodeJson(fname):
    with open(fname, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    dats = []
    outstrs = []
    for i, event in enumerate(data.get("events", [])):
        tStartMs = event.get("tStartMs")
        dDurationMs = event.get("dDurationMs")
        utf8_text = getTxt(event.get("segs", []))
        
        # 将数据以指定格式添加到列表
        dats.append(f'{i + 1}: [{tStartMs}, {dDurationMs}, "{utf8_text}"]')
        outstrs.append(utf8_text)
    
    return dats, outstrs

# 生成字幕文件
def generate_text_files(dats, outstrs):
    with open(output_subtitles_file, "w", encoding="utf-8") as f:
        for line in dats:
            f.write(f"{line}\n")
    
    print(f"字幕信息已保存到 '{output_subtitles_file}' 文件中。")

    with open(output_texts_file, "w", encoding="utf-8") as f:
        for text in outstrs:
            f.write(f"{text}\n")
    
    print(f"字幕文本信息已保存到 '{output_texts_file}' 文件中。")



dats, outstrs = decodeJson(CH_JSON)  # 解析 JSON 字幕文件
generate_text_files(dats, outstrs) #  生成字幕和文本文件